package com.lenovo.leos.filebrowser.engine.operation;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.lenovo.leos.filebrowser.ui.BaseActivity;
import com.lenovo.leos.filebrowser.ui.FileBrowser;
import com.lenovo.leos.filebrowser.ui.FileDialog;
import com.lenovo.leos.filebrowser.R;
import com.lenovo.leos.filebrowser.engine.util.FileClipBoard;
import com.lenovo.leos.filebrowser.engine.util.FileUtil;
import com.lenovo.leos.filebrowser.engine.util.Log;

//[issue] static member 
public class FileRename {
	private static final String TAG = "FileRename";
	
	// msg id
	public static final int MSG_RES_OK = R.string.msg_rename_res_ok;
	public static final int MSG_RES_FAILED = R.string.msg_rename_res_failed;
	
	private static BaseActivity sActivity = null; 
	private static String newName;
	
	//add by xieqm 110309
	public static String getNewName(){
		return newName;
	}
	//end
	
	public static void renameFile(BaseActivity activity, File file) {
		Log.i(TAG, "==> renameFile");

		if (null == activity 
				|| null == file || !file.exists()) {
			Log.e(TAG, "invalid parameter in renameFile");
			return;
		}else {
			sActivity = activity;
			
			checkThenRename(file);
		}
	}

	// after confirming, we can not rename a file with an existed folder name
	// or rename a foler with an existed file name
	// in android, java just regard them as same file.
	private static void checkThenRename(final File file) {
		Log.i(TAG, "==> new checkThenRename");
		if (null == sActivity) {
			Log.e(TAG, "sActivity is null in checkThenRename");
			return;
		}

		LayoutInflater inflater = LayoutInflater.from(sActivity);

		final View content = inflater.inflate(R.layout.dlg_content_newname,null);
		final TextView tv = (TextView) content.findViewById(R.id.filename_view);
		final EditText et = (EditText) content.findViewById(R.id.filename_edit);

		tv.setText(R.string.dlg_rename_msg_input);
		et.setText(file.getName());
		et.setFilters(new InputFilter[] { new InputFilter.LengthFilter(FileUtil.FILE_NAME_NUM_MAX) });

		if (file.isFile()) {
			et.setSelection(0, FileUtil.getFileNameWithoutExt(file.getName()).length());
		} else {
			et.setSelectAllOnFocus(true);
		}

		final Runnable reOpen = new Runnable() {
			// @Override
			public void run() {
				Log.i(TAG, "==> run");
				// TODO Auto-generated method stub
				checkThenRename(file);
			}
		};

		DialogInterface.OnClickListener okListener = new DialogInterface.OnClickListener() {
			// @Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				final String name = et.getText().toString();

				if (FileUtil.getFileNameWithoutExt(name).length() > 0
						&& name.length() <= FileUtil.FILE_NAME_NUM_MAX) {

					if (file.getName().equals(name)) {
						Log.i(TAG, "the name is not changed");
					} else if (!FileUtil.isNameUseable(name, file.isDirectory())) {
						// case: bad name
						Toast.makeText(sActivity, R.string.namebad, Toast.LENGTH_SHORT).show();
						sActivity.postRunnable(reOpen);
					} else if (file.isFile() && !FileUtil.getExtension(name).equals(
									FileUtil.getExtension(file.getName()))) {
						
						// case: [file][extension changed]
						DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {
								File f = new File(file.getParent() + "/" + name);

								if (f.exists()) {
									// case [file] [extension changed] [existed]
									DialogInterface.OnClickListener okListener = new DialogInterface.OnClickListener() {
										// @Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											Log.i(TAG, "==> onClick");
											// TODO Auto-generated method stub
											sActivity.postRunnable(reOpen);
										}
									};
									FileDialog.DialogButton dbp = new FileDialog.DialogButton(
											R.string.alert_dialog_ok,
											okListener);

									FileDialog.showMsgWithOneButton(
													sActivity,
													R.string.dlg_rename_title,
													R.string.dlg_rename_msg_file_existed,
													dbp);
								} else {
									renameFile(file.getParent(),file.getName(), name);
								}
							}
						};

						FileDialog.DialogButton dbp = new FileDialog.DialogButton(
								R.string.alert_dialog_ok, listener);
						FileDialog.DialogButton dbn = new FileDialog.DialogButton(
								R.string.alert_dialog_cancel, null);

						FileDialog.showMsgWithTwoButton(sActivity,
								R.string.dlg_rename_title,
								R.string.dlg_rename_msg_change_ext, dbp, dbn);
					} else {
						// case: [existed]
						File f = new File(file.getParent() + "/" + name);
						Log.i(TAG, "old file is dir"
								+ String.valueOf(file.isDirectory()));
						Log.i(TAG, "new file is dir"
								+ String.valueOf(f.isDirectory()));
						if (f.exists()) {
							DialogInterface.OnClickListener okListener = new DialogInterface.OnClickListener() {

								// @Override
								public void onClick(DialogInterface dialog,
										int which) {
									Log.i(TAG, "==> onClick");
									// TODO Auto-generated method stub
									sActivity.postRunnable(reOpen);
								}
							};
							FileDialog.DialogButton dbp = new FileDialog.DialogButton(
									R.string.alert_dialog_ok, okListener);

							FileDialog.showMsgWithOneButton(sActivity,
									R.string.dlg_rename_title,
									R.string.dlg_rename_msg_file_existed, dbp);
						} else {
							renameFile(file.getParent(), file.getName(), name);
						}
					}
				} else if (name.length() > FileUtil.FILE_NAME_NUM_MAX) {
					Toast.makeText(sActivity, R.string.name_too_long,
							Toast.LENGTH_SHORT).show();
					sActivity.postRunnable(reOpen);
				}else {
					Toast.makeText(sActivity, R.string.nameempty,
							Toast.LENGTH_SHORT).show();
					sActivity.postRunnable(reOpen);
				}
			}
		};

		FileDialog.DialogButton dbp = new FileDialog.DialogButton(
				R.string.alert_dialog_ok, okListener);
		FileDialog.showMsg(sActivity, R.string.dlg_rename_title,
				FileDialog.INVALID_RID, content, dbp, null,
				FileDialog.DEFAULT_BUTTON_CANCEL);
	}
	
	
	private static void renameFile(String path, String oldname, String newname) {
		Log.d(TAG, "==> renameFile");
		//add 2010-12-23 by xieqm
		boolean flag = true;
		File file = new File(path + "/" + oldname);
		//add by xieqm 110309
		if(newname!=null){
			newName = newname;
		}
		//end	
		Log.d(TAG, "@@@@@@@@@" + newname +"########" + file.isFile());
		if(file.isFile()){
			if(newname.contains(".")){
				Log.d(TAG, "%%%%%%%%%%" + newname);
				int index = newname.indexOf(".");
				int length = newname.substring(0,index).trim().length();
				if(length == 0){
					Toast.makeText(sActivity, R.string.nameempty, Toast.LENGTH_LONG).show();
					flag = false;
				}else{
					flag = true;
				}
			}else{
				int nameLength = newname.trim().length();
				if(nameLength == 0){
					Toast.makeText(sActivity, R.string.nameempty, Toast.LENGTH_LONG).show();
					flag = false;
				}else{
					flag = true;
				}
			}
		}
		if(flag){
			if (!oldname.equals(newname)) {//end

				File oldfile = new File(path + "/" + oldname);
				File newfile = new File(path + "/" + newname);
				
				FileClipBoard fcb = FileClipBoard.getInstance();
				boolean inClip = fcb.hasIt(oldfile);

				if (inClip)
					fcb.removeFile(oldfile);
				
				boolean ret = oldfile.renameTo(newfile);
				if (ret) {				
					Toast.makeText(sActivity, R.string.tst_rename_change_ok, 3).show(); 

					// [improve] 
					if (newfile.isDirectory()) {
						Log.d(TAG, "to broadcast : "+ oldfile.getAbsolutePath());
//						sActivity.sendBroadcast(new Intent(
//								Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
//										.fromFile(oldfile)));
	//
//						Log.d(TAG, "to broadcast : "+ newfile.getAbsolutePath());
//						sActivity.sendBroadcast(new Intent(
//								Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
//										.fromFile(newfile)));
						FileUtil.notifyMediaScanner(sActivity, null);
					} else {
						
						// [improve]comment below code for a strange issue
						// after rename an image file, the old file still is there
						if (needBroadCast(oldname)) {
							Log.d(TAG, "[notify mediascanner] rename one file : old name is " + oldfile.getAbsolutePath());
							FileUtil.notifyMediaScanner(sActivity, oldfile);	
						}
						
						if (needBroadCast(newname)) {
							Log.d(TAG, "[notify mediascanner] rename one file : new name is " + newfile.getAbsolutePath());
							FileUtil.notifyMediaScanner(sActivity, newfile);	
						}
					}
					
					// send ok msg
					sActivity.sendEmptyMsg(MSG_RES_OK);

				} else {
					if (inClip)
						fcb.addFile(oldfile);
					Toast.makeText(sActivity, R.string.rename_file_fail, 3).show();
					
					// send failed msg
					sActivity.sendEmptyMsg(MSG_RES_FAILED);
				}
			}
		}
	}
	
	private static boolean needBroadCast(String name){
		if (null == name || 0 == name.length())
			return false;

		String type = FileUtil.getMimeTypeOfFile(sActivity, name);
		if(type != null){ 
			if(type.startsWith("image") 
					|| type.startsWith("audio") 
					|| type.startsWith("video")){
				return true;
			}
		}
		
		return false;
	}
		
}
